import React, { useState, useEffect } from 'react';
import { Toast } from 'antd-mobile';
import qs from 'querystring';

export default function useHttpHook({
  url,
  method = 'Post',
  headers,
  body = {},
  watch = [],
}: {
  url: string;
  method: string;
  headers?: any;
  body?: any;
  watch?: any[];
}) {
  const [resData, setResData] = useState(null);
  const [resState, setResState] = useState(true);
  async function sendRequest() {
    setResState(true);
    const defaultHeader = {
      'Content-type': 'application/json',
    };
    let params: any;
    if (method.toUpperCase() === 'GET') {
      url += '?';
      url += qs.stringify(body);
      // let keyList = Object.keys(body);
      // keyList.forEach((item, index) => {
      //   if (body[item].constructor.name === 'Array') {
      //     body[item].forEach((dataI: any, indexD: number) => {
      //       url += `${item}[${indexD}]=${dataI}${
      //         indexD !== body[item].length - 1 ? '&' : ''
      //       }`;
      //     });
      //     if (index !== keyList.length - 1 && body[item].length > 0) {
      //       url += '&';
      //     }
      //   } else {
      //     url += item + '=' + body[item];
      //     if (index !== keyList.length - 1) {
      //       url += '&';
      //     }
      //   }
      // });
      params = undefined;
    } else {
      params = {
        method,
        headers: {
          ...headers,
          ...defaultHeader,
        },
        body: qs.stringify(body),
      };
    }
    return new Promise((resolve, reject) => {
      fetch(url, params)
        .then((res) => res.json())
        .then((res) => {
          if (res.code === 200) {
            resolve(res.data);
            setResData(res.data);
          } else {
            reject(res.message);
            Toast.fail(res.message);
          }
        })
        .catch((err) => {
          reject(err.message);
          Toast.fail(err.message);
        })
        .finally(() => {
          setResState(false);
        });
    });
  }

  useEffect(() => {
    sendRequest();
  }, watch);

  return [resData, resState];
}
